<!--
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2020 陈尼克 all rights reserved.
 * 版权所有，侵权必究！
 *
-->

<template>
  <div class="login">
    <s-header
      :name="state.type == 'login' ? '登录' : '注册'"
      :back="'/home'"
    ></s-header>
    <img class="logo" :src="logo" alt="" />
    <div v-if="state.type == 'login'" class="login-body login">
      <van-form @submit="onSubmit">
        <van-field
          v-model="state.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="state.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <!-- <van-field
          center
          clearable
          label="验证码"
          placeholder="输入验证码"
          v-model="state.verify"
        >
          <template #button>
            <vue-img-verify ref="verifyRef" />
          </template>
        </van-field> -->
        <div style="margin: 16px">
          <div class="link-register" @click="toggle('register')">立即注册</div>
          <div class="link-register" style="margin-left: 5px;" @click="toPwd">忘记密码</div>
          <van-button round block color="#1baeae" native-type="submit"
            >登录</van-button
          >
        </div>
      </van-form>
    </div>
    <div v-else class="login-body register">
      <van-form @submit="onSubmit">
        <van-field
          v-model="state.username1"
          name="username1"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="state.nickname"
          name="nickname"
          label="姓名"
          placeholder="姓名"
        />
        <van-field
          v-model="state.password1"
          type="password"
          name="password1"
          label="密码"
          placeholder="密码"
          :rules="[
            { required: true, message: '请填写密码' },
            {
              pattern:
                /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/,
              message:
                '密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8',
              trigger: 'onBlur',
            },
          ]"
        />
        <van-field
          v-model="state.confirm_password"
          type="password"
          name="confirm_password"
          label="确认密码"
          placeholder="确认密码"
          :rules="pwdRule(state.confirm_password)"
        />
        <van-field
          v-model="state.we_chat"
          name="we_chat"
          label="微信号"
          placeholder="微信号"
        />
        <!-- <van-field
          v-model="state.qq"
          name="qq"
          label="QQ"
          placeholder="QQ"
          :rules="[{ required: true, message: '请填写QQ' }]"
        /> -->
        <van-field
          v-model="state.tel"
          name="tel"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { required: true, message: '请填写手机号' },
            {
              pattern: /^1[3456789]\d{9}$/,
              message: '手机号码格式错误！',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field name="radio" label="用户类型">
          <template #input>
            <van-checkbox-group v-model="state.roletype">
              <!-- <van-radio name="2">个人</van-radio> -->
              <van-checkbox name="3">供应商</van-checkbox>
              <van-checkbox name="6">需求商</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
        <!-- <van-field
          center
          clearable
          label="验证码"
          placeholder="输入验证码"
          v-model="state.verify"
        >
          <template #button>
            <vue-img-verify ref="verifyRef" />
          </template>
        </van-field> -->
        <div style="margin: 16px">
          <div class="link-login" @click="toggle('login')">已有登录账号</div>
          <van-button round block color="#1baeae" native-type="submit"
            >注册</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import sHeader from "@/components/SimpleHeader.vue";
import vueImgVerify from "@/components/VueImageVerify.vue";
import { login, register, getUserInfo } from "@/service/user";
import { setLocal } from "@/common/js/utils";
import { showSuccessToast, showFailToast, showToast } from "vant";
import logo from "@/assets/logo2.jpg";
const verifyRef = ref(null);
const router = useRouter();
const state = reactive({
  username: "",
  password: "",
  username1: "",
  password1: "",
  type: "login",
  imgCode: "",
  verify: "",
  we_chat: "",
  qq: "",
  tel: "",
  roletype: [],
  confirm_password: "",
  nickname: "",
});

onMounted(async () => {
  console.log(router);
})

// 切换登录和注册两种模式
const toggle = (v) => {
  state.type = v;
  state.verify = "";
};

const isConfirmPassword = (value) => {
  return state.password1 === value;
};

const pwdRule = (obj) => {
  return [
    { required: true, message: "请填写密码" },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/,
      message:
        "密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8",
      trigger: "onBlur",
    },
    {
      obj,
      validator: isConfirmPassword,
      message: "两遍密码不相同",
      trigger: "onBlur",
    }
  ]
};

const toPwd = () => {
  router.push({ path: `/pwd` });
}

// 提交登录或注册表单
const onSubmit = async (values) => {
  // state.imgCode = verifyRef.value.state.imgCode || "";
  // if (state.verify.toLowerCase() != state.imgCode.toLowerCase()) {
  //   showFailToast("验证码有误");
  //   return;
  // }

  if (state.type == "login") {
    try {
      const data = await login({
        username: values.username,
        password: values.password,
      });

      setLocal("access_token", `Bearer ${data.access_token}`);
      setLocal("refresh_token", `Bearer ${data.refresh_token}`);

      showToast({
        message: "登录成功",
        className: "particulars-detail-popup",
      });
    } catch (err) {
      console.log(err);
      showToast({
        message: "账号或密码错误！",
        className: "particulars-detail-popup",
      });
      return;
    }

    // 需要刷新页面，否则 axios.js 文件里的 token 不会被重置
    // window.location.href = "/home";
    setTimeout(() => {
      router.push({ path: `/home` });
    }, 500)
  } else {
    const finalCheckPwd =
      /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;

    // 两次密码必须相同
    if (values.password1 !== values.confirm_password) {
      showToast({
        message: "两遍密码必须相同",
        className: "particulars-detail-popup",
      });
      return;
    }

    const checkPwd = finalCheckPwd.test(values.password1);

    if(!checkPwd) {
      showToast({
        message: "密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8",
        className: "particulars-detail-popup",
      });
      return
    }

    const name = values.nickname === "" ? values.username1 : values.nickname;
    const res = await register({
      username: values.username1,
      password: values.password1,
      we_chat: values.we_chat,
      qq: "待填写",
      tel: values.tel,
      roletype: state.roletype,
      nickname: name,
      confirm_password: values.confirm_password,
      group_ids: state.roletype,
    })
      .then((res) => {
        showToast({
          message: res.message ? res.message : '注册成功',
          className: "particulars-detail-popup",
        });
        state.type = "login";
        state.verify = "";
      })
      .catch((err) => {
        let e = "";
        for (const key in err.response.data.message) {
          if (Object.hasOwnProperty.call(err.response.data.message, key)) {
            const el = err.response.data.message[key];

            e += el;
          }
        }
        showToast({
          message: e,
          className: "particulars-detail-popup",
        });
      });
  }
};
</script>

<style lang="less">
.login {
  .logo {
    width: 120px;
    height: 120px;
    display: block;
    margin: 80px auto 20px;
  }
  .login-body {
    padding: 0 20px;
  }
  .login {
    .link-register {
      font-size: 14px;
      margin-bottom: 20px;
      color: #1989fa;
      display: inline-block;
    }
  }
  .register {
    .link-login {
      font-size: 14px;
      margin-bottom: 20px;
      color: #1989fa;
      display: inline-block;
    }
  }
  .verify-bar-area {
    margin-top: 24px;
    .verify-left-bar {
      border-color: #1baeae;
    }
    .verify-move-block {
      background-color: #1baeae;
      color: #fff;
    }
  }
  .verify {
    > div {
      width: 100%;
    }
    display: flex;
    justify-content: center;
    .cerify-code-panel {
      margin-top: 16px;
    }
    .verify-code {
      width: 40% !important;
      float: left !important;
    }
    .verify-code-area {
      float: left !important;
      width: 54% !important;
      margin-left: 14px !important;
      .varify-input-code {
        width: 90px;
        height: 38px !important;
        border: 1px solid #e9e9e9;
        padding-left: 10px;
        font-size: 16px;
      }
      .verify-change-area {
        line-height: 44px;
      }
    }
  }
}
</style>
